using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.customers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.customers
{
    /// <summary>
    /// 批量逻辑删除客户命令处理器
    /// </summary>
    public class BatchDeleteCustomersCommandHandler : IRequestHandler<BatchDeleteCustomersCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Customer> _customerRepository;
        private readonly ILogger<BatchDeleteCustomersCommandHandler> _logger;

        public BatchDeleteCustomersCommandHandler(
            IBaseRepository<Customer> customerRepository,
            ILogger<BatchDeleteCustomersCommandHandler> logger)
        {
            _customerRepository = customerRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量逻辑删除客户命令
        /// </summary>
        /// <param name="request">批量删除客户命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(BatchDeleteCustomersCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始批量逻辑删除客户，ID数量: {Count}, IDs: {Ids}", 
                    request.Ids.Count, string.Join(",", request.Ids));

                // 获取所有需要删除的客户（排除已删除的）
                var customersToDelete = await _customerRepository.GetAll()
                    .Where(c => request.Ids.Contains(c.Id) && !c.IsDeleted)
                    .ToListAsync(cancellationToken);

                if (!customersToDelete.Any())
                {
                    _logger.LogWarning("没有找到需要删除的客户，IDs: {Ids}", string.Join(",", request.Ids));
                    return ApiResult<bool>.Error("没有找到需要删除的客户");
                }

                // 检查是否有启用状态的客户
                var enabledCustomers = customersToDelete.Where(c => c.Status == "启用").ToList();
                if (enabledCustomers.Any())
                {
                    var enabledNames = string.Join(",", enabledCustomers.Select(c => c.Name));
                    _logger.LogWarning("批量删除中包含启用状态的客户，无法删除: {Names}", enabledNames);
                    return ApiResult<bool>.Error($"以下客户为启用状态，无法删除：{enabledNames}，请先停用后再删除");
                }

                // 检查是否有客户存在下级客户关系
                var customerIds = customersToDelete.Select(c => c.Id).ToList();
                var hasSubordinateCustomers = await _customerRepository.GetAll()
                    .Where(c => customerIds.Contains(c.SuperiorCustomerId ?? 0) && !c.IsDeleted)
                    .Select(c => new { c.SuperiorCustomerId, c.Name })
                    .ToListAsync(cancellationToken);

                if (hasSubordinateCustomers.Any())
                {
                    var customerNamesWithSubordinates = customersToDelete
                        .Where(c => hasSubordinateCustomers.Any(sub => sub.SuperiorCustomerId == c.Id))
                        .Select(c => c.Name);
                    
                    var customerNamesStr = string.Join(",", customerNamesWithSubordinates);
                    _logger.LogWarning("批量删除中包含有下级客户的客户，无法删除: {Names}", customerNamesStr);
                    return ApiResult<bool>.Error($"以下客户存在下级客户，无法删除：{customerNamesStr}，请先处理下级客户关系");
                }

                // 执行批量逻辑删除
                foreach (var customer in customersToDelete)
                {
                    customer.IsDeleted = true;
                    customer.UpdatedTime = DateTime.Now;
                    customer.UpdatedBy = 1;
                }

                // 执行批量更新操作
                var result = await _customerRepository.UpdateRanger(customersToDelete);

                if (result > 0)
                {
                    var deletedNames = string.Join(",", customersToDelete.Select(c => c.Name));
                    _logger.LogInformation("成功批量逻辑删除客户，删除数量: {Count}, 客户名称: {Names}", 
                        result, deletedNames);
                    
                    return ApiResult<bool>.Success(true, $"成功删除 {result} 个客户");
                }
                else
                {
                    _logger.LogError("批量逻辑删除客户失败，IDs: {Ids}", string.Join(",", request.Ids));
                    
                    return ApiResult<bool>.Error("批量删除客户失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量逻辑删除客户时发生异常，IDs: {Ids}", string.Join(",", request.Ids));
                
                return ApiResult<bool>.Error($"批量删除客户时发生异常: {ex.Message}");
            }
        }
    }
}
